using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Configuration;
using System.Collections;
using System.Globalization;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.Xml.Serialization;
using Microsoft.ApplicationBlocks.Data;
using Microsoft.AceEngineering.SPM.SPMBusinessLayer;
using Microsoft.AceEngineering.SPM.SPMCustomDataEntity;

public partial class Workflow_Tasks : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["user"] == null)
            ValidateUser();
        else
        {
            UserCDE userData = (UserCDE)Session["user"];
            if (userData.Time.AddMinutes(Int32.Parse(ConfigurationManager.AppSettings["AbsoluteExpiration"].ToString())) <= DateTime.Now)
                ValidateUser();
        }

        if (!Page.IsPostBack)
        {
            int appID = 0;
            bool blAppID = Int32.TryParse(Request.QueryString["ID"], out appID);

            if (blAppID)
            {
                try
                {
                    hfAppID.Value = appID.ToString();

                    pnlSearch.Visible = false;
                    pnlAppTask.Visible = true;
                    btnCancel.ToolTip = "Back to View Application Data";

                    BindAppInfo(appID);
                    BindRepeaters(appID);
                }
                catch
                {
                    Response.Redirect("~/Workflow/Tasks.aspx");
                }
            }
            else
            {
                btnCancel.ToolTip = "Back to Update Task Status - Application Quick Search";
            }
        }
    }

    private string GiveMeAlias(string domainAndAlias)
    {
        domainAndAlias = domainAndAlias.ToLower();
        char[] strSeperator = new char[] { '\\' };
        string[] aryAuthUser = new string[2];
        aryAuthUser = domainAndAlias.Split(strSeperator);
        return aryAuthUser[1];
    }

    private void ValidateUser()
    {
        string currAlias = GiveMeAlias(HttpContext.Current.User.Identity.Name);
        UserCDE user = UsersBL.ValidateUser(currAlias);
        if (user.Active)
        {
            Session["user"] = user;
            Session["loginname"] = user.UserAlias;
        }
        else
        {
            Response.Redirect(Request.ApplicationPath + "/Errors/NoAccess.htm");
        }
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            int searchByID;
            int intSearchType = Int32.Parse(rdsearchType.SelectedValue.ToString());

            bool IDFound = Int32.TryParse(txtSearch.Text, out searchByID);
            if (intSearchType == 1)
            {
                try
                {
                    if (IDFound)// Search parameter is an Integer value so search will be either on application name or application id
                        Search(string.Empty, searchByID);
                    else
                        throw new Exception("APMError021");
                }
                catch (Exception ex)
                {
                    string strErrorType = ex.Message.ToString().Substring(0, 8);

                    Page pge = (Page)this.Page;
                    Microsoft.ACEEngineering.Utility.CommonProcess.APMErrorHandling(ex, Request.IsLocal, pge, Session, Request);
                    if (!Request.IsLocal && strErrorType != "APMError")
                    {
                        Server.ClearError();
                        Server.Transfer(Request.ApplicationPath + "/Errors/GenericErrorPage.htm");
                    }
                }
            }
            else
            {
                //Search parameter is a string so search will be on application name
                Search(txtSearch.Text, 0);
            }
        }
        else
        {
            string msg = "Please correct the following:\\n- Required Field: Application Name/ID";
            Page pge = (Page)this.Page;
            Microsoft.ACEEngineering.Utility.CommonProcess.CreateMessageAlert(ref pge, msg, "errorkey");
        }
    }

    protected void Search(string name, int id)
    {
        try
        {
            ArrayList list = ApplicationsBL.GetSearchApplicationData(name, id);

            lstApplicationNames.Items.Clear();
            foreach (ListItem lstTemp in list)
            {
                lstApplicationNames.Items.Add(lstTemp);
            }
            lstApplicationNames.Visible = true;
            lblResult.Visible = true;
            btnGo.Visible = true;
        }
        catch (Exception ex)
        {
            string strErrorType = ex.Message.ToString().Substring(0, 8);

            Page pge = (Page)this.Page;
            Microsoft.ACEEngineering.Utility.CommonProcess.APMErrorHandling(ex, Request.IsLocal, pge, Session, Request);
            if (!Request.IsLocal && strErrorType != "APMError")
            {
                Server.ClearError();
                Server.Transfer(Request.ApplicationPath + "/Errors/GenericErrorPage.htm");
            }
            btnGo.Visible = false;
            lstApplicationNames.Visible = false;
            lblResult.Visible = false;
        }
    }

    protected void btnGo_Click(object sender, EventArgs e)
    {
        if (lstApplicationNames.SelectedIndex != -1)
        {
            int intAppID = Int32.Parse(lstApplicationNames.SelectedValue);
            pnlSearch.Visible = false;
            pnlAppTask.Visible = true;
            pnlLifeCycle.Visible = true;
            pnlError.Visible = false;
            btnSubmit.Visible = true;

            BindAppInfo(intAppID);
            BindRepeaters(intAppID);
        }
        else
        {
            Page pge = (Page)this.Page;
            Microsoft.ACEEngineering.Utility.CommonProcess.CreateMessageAlert(ref pge, "No application was selected.", "errorkey");
        }
    }

    protected void BindAppInfo(int appID)
    {
        ApplicationCDE appInfo = WTRIAssessmentBL.GetApplicationInfoByAppID(appID);

        hfAppID.Value = appID.ToString();
        lblAppID.Text = Microsoft.Security.Application.AntiXss.HtmlEncode(appInfo.ApplicationID.ToString());
        lblAppName.Text = Microsoft.Security.Application.AntiXss.HtmlEncode(appInfo.ApplicationName);
        lblVersion.Text = Microsoft.Security.Application.AntiXss.HtmlEncode(appInfo.Version);

        lblStatus.Text = "<font color='green'>Completed</font>";
        DataSet ds = WTRIAssessmentBL.dsLoadAssessmentDataSet("SPM_spGetAppLifeCyclesStatusByAppID", appID);
        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            if (dr["status"].ToString() == "red")
            {
                lblStatus.Text = "<font color='red'>In Progress</font>";
            }
        }
        ValidateUserContact(appID, Session["loginname"].ToString());
    }

    private void ValidateUserContact(int intAppid, string strUserAlias)
    {
        if (ConfigurationManager.AppSettings["RestictUpdatesToContacts"].ToString().ToUpper() == "TRUE")
        {
            int qty = WTRIAssessmentBL.RestictUpdatesToContacts(intAppid, Session["loginname"].ToString());
            if (qty == 0)
            {
                btnSubmit.Visible = false;
                pnlError.Visible = true;
                lblStatus.Text = "Error";
                lblError.Text = "Insufficient Permissions to Update";
            }
        }
    }

    protected void BindRepeaters(int appID)
    {
        DataTable ds = WTRIAssessmentBL.dsLoadAssessmentDataSet("SPM_spGetAppLifeCyclesByAppID", appID).Tables[0];

        if (ds.DefaultView.Count != 0)
        {
            rptLifeCycle.DataSource = ds;
            rptLifeCycle.DataBind();
        }
        else
        {
            lblStatus.Text = "Error";
            pnlError.Visible = true;
            btnSubmit.Visible = false;
            pnlLifeCycle.Visible = false;

            if (ValidateAssessmentTaken(appID))
                lblError.Text = "No tasks were assigned for the score range this application generated.";
            else
                lblError.Text = "The responses for this application have not been submitted and no tasks have been generated.";
        }
    }    

    protected void SubmitClick(object source, EventArgs e)
    {
        if (Page.IsValid)
        {
            int intAppID = Int32.Parse(hfAppID.Value);
            UpdateDates();
            BindAppInfo(intAppID);
            BindRepeaters(intAppID);
        }
        if (!Page.IsValid)
        {
            StringBuilder msg = new StringBuilder("Please correct the following:\\n");
            // Loop through all validation controls to see which
            // generated the errors.
            foreach (IValidator aValidator in this.Validators)
            {
                if (!aValidator.IsValid)
                {
                    msg.Append("- " + aValidator.ErrorMessage + "\\n");
                }
            }
            Page pge = (Page)this.Page;
            Microsoft.ACEEngineering.Utility.CommonProcess.CreateMessageAlert(ref pge, msg.ToString(), "errorkey");
        }
    }

    protected void CancelClick(object source, EventArgs e)
    {
        if (Request.QueryString["id"] != null)
            Response.Redirect("~/Application/ApplicationDataEntryView.aspx?id=" + hfAppID.Value);
        else
        {
            Session["search"] = null;
            pnlSearch.Visible = true;
            hfAppID.Value = null;
            pnlAppTask.Visible = false;
        }
    }

    private bool ValidateAssessmentTaken(int intAppID)
    {
        int score = WTRIAssessmentBL.GetValidateScoreExist(intAppID);
        if (score == -1)
        {
            return false;
        }
        else
        {
            return true;
        }
    }

    protected void rptLifeCycle_ItemDataBound(object source, RepeaterItemEventArgs e)
    {
        DataView dv = WTRIAssessmentBL.dsLoadAssessmentDataSet("SPM_spGetAppTasksByAppID", Int32.Parse(hfAppID.Value)).Tables[0].DefaultView;

        foreach (RepeaterItem ri in rptLifeCycle.Items)
        {
            TextBox txtLCID = (TextBox)ri.FindControl("txtLifeCycleID");
            dv.RowFilter = "LifeCycleID='" + txtLCID.Text.ToString() + "'";

            if (dv.Count == 0)
            {
                Label lblMessage = (Label)ri.FindControl("lblNoTasks");
                lblMessage.Text = "No Tasks";
            }
            else
            {
                Repeater rptAppTask = (Repeater)ri.FindControl("rptTasks");
                rptAppTask.DataSource = dv;
                rptAppTask.DataBind();

                foreach (RepeaterItem riT in rptAppTask.Items)
                {
                    TextBox txtCompleteDate = (TextBox)riT.FindControl("txtCompletedDate");
                    txtCompleteDate.Text = txtCompleteDate.Text.Replace(" 12:00:00 AM", "");

                    PlaceHolder phDate = (PlaceHolder)riT.FindControl("phCompletedDate");
                    Image imgDate = new Image();
                    imgDate.ImageUrl = (Request.ApplicationPath + "/Images/calendar.png");
                    imgDate.AlternateText = "Select date from calendar.";
                    imgDate.ID = "imgCompleteDate";
                    imgDate.Width = Unit.Pixel(20);
                    imgDate.Height = Unit.Pixel(20);
                    phDate.Controls.Add(imgDate);
                }
            }
        }
    }

    private void UpdateDates()
    {
        try
        {
            DataTable dt = new DataTable("Dates");
            DataColumn[] column = new DataColumn[4];
            column[0] = new DataColumn("ApplicationTaskID", System.Type.GetType("System.String"));
            dt.Columns.Add(column[0]);
            column[1] = new DataColumn("ModifiedBy", System.Type.GetType("System.String"));
            dt.Columns.Add(column[1]);
            column[2] = new DataColumn("ModifiedDate", System.Type.GetType("System.DateTime"));
            dt.Columns.Add(column[2]);
            column[3] = new DataColumn("CompletedDate", System.Type.GetType("System.DateTime"));
            column[3].AllowDBNull = true;
            dt.Columns.Add(column[3]);

            DataSet dsXML = new DataSet("SPMApplicationTaskTracking");
            dsXML.Tables.Add(dt);

            foreach (RepeaterItem ri in rptLifeCycle.Items)
            {
                int i = 0;
                int cnt = 0;

                Repeater rptTask = (Repeater)ri.FindControl("rptTasks");
                foreach (RepeaterItem rptT in rptTask.Items)
                {
                    i = rptTask.Items.Count;

                    TextBox txtAppTaskID = (TextBox)rptT.FindControl("txtTaskID");
                    string strAppTaskID = txtAppTaskID.Text.ToString().ToUpper();

                    TextBox txtCompleted = (TextBox)rptT.FindControl("txtCompletedDate");
                    string strCompletedDate = txtCompleted.Text.ToString();

                    DataRow[] dr = new DataRow[i];
                    if (!string.IsNullOrEmpty(strCompletedDate))
                    {
                        try
                        {
                            DateTime dtCompletedDate;// = Convert.ToDateTime(strCompletedDate);
                            bool blDate = DateTime.TryParse(strCompletedDate, out dtCompletedDate);
                            if (!blDate)
                                throw new Exception();

                            if (dtCompletedDate < Convert.ToDateTime("1/1/1753"))
                                throw new Exception();

                            dr[cnt] = dt.NewRow();
                            dr[cnt]["ApplicationTaskID"] = strAppTaskID;
                            dr[cnt]["ModifiedBy"] = Session["loginname"].ToString();
                            dr[cnt]["ModifiedDate"] = System.DateTime.Now.Date.ToShortDateString();
                            dr[cnt]["CompletedDate"] = strCompletedDate;
                            dt.Rows.Add(dr[cnt]);

                        }
                        catch
                        {
                            string msg = "Please correct the following:\\n- Invalid Input: Completed Date";
                            Page pge = (Page)this.Page;
                            Microsoft.ACEEngineering.Utility.CommonProcess.CreateMessageAlert(ref pge, msg, "errorkey");
                        }
                    }
                    cnt = cnt + 1;
                }
            }

            System.IO.MemoryStream xmlStream = new System.IO.MemoryStream();
            dsXML.WriteXml(xmlStream, XmlWriteMode.IgnoreSchema);
            xmlStream.Position = 0;
            StreamReader xmlTaskStream = new StreamReader(xmlStream);
            string strXML = xmlTaskStream.ReadToEnd().ToString();

            strXML = Regex.Replace(strXML, "T00:00:00-0[0-9]:00", "");

            WTRIAssessmentBL.UpdateApplicationTaskDates(strXML, Int32.Parse(hfAppID.Value), Session["loginname"].ToString());

            Page page = (Page)this.Page;
            Microsoft.ACEEngineering.Utility.CommonProcess.CreateMessageAlert(ref page, "The dates were successfully saved into the system.", "errorkey");
        }
        catch
        {
            StringBuilder msg = new StringBuilder("Please correct the following:\\n");
            // Loop through all validation controls to see which
            // generated the errors.
            foreach (IValidator aValidator in this.Validators)
            {
                if (!aValidator.IsValid)
                {
                    msg.Append("- " + aValidator.ErrorMessage + "\\n");
                }
            }
            Page pge = (Page)this.Page;
            Microsoft.ACEEngineering.Utility.CommonProcess.CreateMessageAlert(ref pge, msg.ToString(), "errorkey");
        }
    }

    /// <summary>
    /// This method will convert the Date Value to color Status. The color value will be picked from web.config.
    /// </summary>
    /// <param name="completedate"></param>
    /// <returns></returns>
    public string ReturnColorStatus(string completedate)
    {
        if (completedate.Trim().Length != 0 )
            return ConfigurationManager.AppSettings["completed"].ToString();
        else
            return ConfigurationManager.AppSettings["pending"].ToString();
    }
}
